<template>
  <div id="app">
    编号: <input type="text" v-model.number.trim="id"> 品牌: <input type="text" v-model.number.trim="name"> <button @click="add">添加</button>
    <table class="tb">
      <tr>
        <th>编号</th>
        <th>品牌名称</th>
        <th>创立时间</th>
        <th>操作</th>
      </tr>
      <!-- 循环渲染的元素tr -->
      <tr v-for="(item, index) in list" :key="item.id">
        <td> {{ item.id }} </td>
        <td> {{ item.name }} </td>
        <td> {{ item.time }} </td>
        <td>
          <button @click="del(index)" >删除</button>
        </td>
      </tr>

      <tr v-if="!list.length">
        <td colspan="4">没有数据咯~</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      list: [
        { id: 1, name: '奔驰', time: '2020-08-01' },
        { id: 2, name: '宝马', time: '2020-08-02' },
        { id: 3, name: '奥迪', time: '2020-08-03' }
      ],
      id: '',
      name: ''
    }
  },

  created () {

  },

  methods: {
    add () {
      if (this.id === '' || this.name === '') {
        return alert('内容不能为空，请仔细核对！')
      }
      if (this.list.every(item => this.id !== item.id)) {
        this.list.push({ id: this.id, name: this.name, time: this.addDate() })
      } else {
        alert('编号重复，请仔细核对！')
      }
    },
    del (index) {
      this.list.splice(index, 1)
    },
    addDate () {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month > 10 ? date.month : '0' + date.month
      const newday = date.date > 10 ? date.date : '0' + date.date
      return date.year + '-' + newmonth + '-' + newday
    }
  }
}
</script>

<style>
#app {
  width: 600px;
  margin: 10px auto;
}

.tb {
  border-collapse: collapse;
  width: 100%;
}

.tb th {
  background-color: #0094ff;
  color: white;
}

.tb td,
.tb th {
  padding: 5px;
  border: 1px solid black;
  text-align: center;
}

.add {
  padding: 5px;
  border: 1px solid black;
  margin-bottom: 10px;
}
</style>
